package com.nuanshui.heatedloan.fund.biz.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.nuanshui.framework.consts.TransactionManagerType;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.baseservice.facade.OrderNumGenerate;
import com.nuanshui.heatedloan.baseservice.service.CommonServiceImpl;
import com.nuanshui.heatedloan.constant.*;
import com.nuanshui.heatedloan.dal.IdTypeHandler;
import com.nuanshui.heatedloan.dubbo.DubboResponse;
import com.nuanshui.heatedloan.dubbo.DubboResponseCode;
import com.nuanshui.heatedloan.fund.biz.dal.mapper.UserAccountBillMapper;
import com.nuanshui.heatedloan.fund.biz.dal.mapper.UserBindAccountMapper;
import com.nuanshui.heatedloan.fund.biz.dal.mapper.UserFreezeFundActionMapper;
import com.nuanshui.heatedloan.fund.biz.dal.mapper.UserFundActionMapper;
import com.nuanshui.heatedloan.fund.constant.AccountBillStatus;
import com.nuanshui.heatedloan.fund.enums.PaymentBizType;
import com.nuanshui.heatedloan.fund.enums.PlatformEnum;
import com.nuanshui.heatedloan.fund.facade.JadeCurrencyService;
import com.nuanshui.heatedloan.fund.facade.UserFundActionService;
import com.nuanshui.heatedloan.fund.form.UseFundForm;
import com.nuanshui.heatedloan.fund.form.UseJadeCurrencyForm;
import com.nuanshui.heatedloan.fund.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;



@Service
@Transactional(readOnly = true,value = TransactionManagerType.FUND_TRANSACTION_MANAGER)
public class UserFundActionServiceImpl extends CommonServiceImpl implements UserFundActionService {

	@Autowired
	private UserFundActionMapper userFundActionMapper;

	@Autowired
	private UserAccountBillMapper userAccountBillMapper;

	@Reference(url = GlobalParam.BASESERVICE_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.BASESERVICE_DUBBO_SERVER_VERSION)
	private OrderNumGenerate orderNumGenerate;

	@Autowired
	private UserBindAccountMapper userBindAccountMapper;

	@Autowired
	private UserFreezeFundActionMapper userFreezeFundActionMapper;
	@Autowired
	private JadeCurrencyService jadeCurrencyService;

	public static final String NAME = "保证金";

	private static final Logger logger = LoggerFactory.getLogger("user_fund");

	@Override
	public DubboResponse loadTotalFund(String userId) {
		Long money = userFundActionMapper.loadTotalFund(userId);
		if (money == null)
			money = 0L;
		return success(money);
	}

	@Override
	@Transactional(value = TransactionManagerType.FUND_TRANSACTION_MANAGER)
	public void saveUserFundAction(UserFundAction userFundAction) {
		// 插入账单记录表
		int type = 0;
		if (PlatformEnum.PLATFORM_BK.getName().equals(userFundAction.getPlatform())) {
			type = 3;
		} else if (PlatformEnum.PLATFORM_ALI.getName().equals(userFundAction.getPlatform())) {
			type = 1;
		} else if (PlatformEnum.PLATFORM_WX.getName().equals(userFundAction.getPlatform())) {
			type = 2;
		}
		UserAccount userAccount = userBindAccountMapper.loadUserPayAccount(userFundAction.getUserId(), type);
		if (userAccount == null)
			error("没有绑定账号不能提现");
		UserAccountBill userAccountBill = new UserAccountBill();
		userAccountBill.setUserId(userFundAction.getUserId());
		userAccountBill.setDealNum(userFundAction.getDealNum());
		userAccountBill.setMoney(userFundAction.getMoney());
		userAccountBill.setName("提现");
		userAccountBill.setStatus(AccountBillStatus.AUDIT);
		userAccountBill.setType(PaymentBizType.WITHDRAW_CASH.getCode());
		userAccountBill.setBizId(userAccount.getId());
		userAccountBill.setPlatform(userFundAction.getPlatform());
		userAccountBillMapper.insertBillRecord(userAccountBill);
		userFundAction.setBizId(userAccountBill.getId());
		userFundActionMapper.saveUserFundAction(userFundAction);

	}

	@Override
	public List<UserFundAction> findByActionType(String userId, Integer actionType, int status, Pageable pager) {
		return userFundActionMapper.findByActionType(userId, actionType, status, pager);
	}

	@Override
	public List<UserFundAction> findCompleteUserFundActionByActionType(String userId, Integer actionType) {
		return userFundActionMapper.findCompleteUserFundActionByActionType(userId, actionType);
	}

	@Override
	public UserFundAction loadCreditUserFundAction(String orderNum) {
		return null;
	}

	@Override
	@Transactional(value = TransactionManagerType.FUND_TRANSACTION_MANAGER)
	public String loadRechargeOrderNum(Long money, String curUserId) {
		if (money == null || money <= 0)
			error("请输入要充值的金额");
		// 获取订单号
		String orderNum = orderNumGenerate.getDealNum(PaymentBizType.RECHARGE.getCode());
		// 生成用户资金流转记录
		UserFundAction userFundAction = new UserFundAction();
		userFundAction.setActionType(PaymentBizType.RECHARGE.getCode());
		userFundAction.setStatus(FundActionState.CREATE);
		userFundAction.setDealNum(orderNum);
		userFundAction.setUserId(curUserId);
		userFundAction.setMoney(money);
		userFundActionMapper.saveUserFundAction(userFundAction);
		return orderNum;
	}

	@Override
	@Transactional(value = TransactionManagerType.FUND_TRANSACTION_MANAGER)
	public boolean confirmUserRechange(Long money, String orderNum, String payType) {
		synchronized (orderNum) {
			UserFundAction userFundAction = userFundActionMapper.loadUserFundByDealNum(orderNum);
			userFundActionMapper.updateUserFundActionStatus(10, userFundAction.getId());
			userFundActionMapper.updateRechargePayType(payType, userFundAction.getId());
			LogUtil.info(logger, "充值确认成功");
		}
		return true;
	}

	@Override
	@Transactional(value = TransactionManagerType.FUND_TRANSACTION_MANAGER)
	public boolean checkUserCashing(String fundId, Integer isPass, String billId) {
		// TODO Auto-generated method stub
		LogUtil.info(logger, "用户为管理员，正在执行审核是否通过...");
		if (billId == null) {
			billId = IdTypeHandler.encode(userFundActionMapper.getBizIdByFundId(fundId));
		}
		if (fundId == null) {
			fundId = IdTypeHandler.encode(userFundActionMapper.getFundIdByBizId(billId));
		}
		Integer isValidated = userFundActionMapper.validateUserCanbeCashing(fundId);
		if (isValidated == 0) {
			LogUtil.error(logger, "action_type或status不为2！");
			return false;
		}

		Integer status = 2; // 初始状态
		if (isPass == 1) {
			status = 10; // 审核通过的状态
		} else if (isPass == 0) {
			status = -1; // 审核不通过的状态
		} else {
			LogUtil.error(logger, "isPass非0,1的其他数字");
		}
		userFundActionMapper.updateUserCashingStatus(fundId, status);

		Integer status_bill = 1;
		if (isPass == 1) {
			status_bill = 10; // 审核通过的状态
		} else if (isPass == 0) {
			status_bill = -1; // 审核不通过的状态
		} else {
			LogUtil.error(logger, "isPass非0,1的其他数字");
		}
		userAccountBillMapper.updateUserAccountBillStatus(billId, status_bill);
		return true;
	}

	@Override
	public CashingApplyInfo getUserFundActionById(String fundId) {
		// TODO Auto-generated method stub
		LogUtil.info(logger, "正在执行查找。。。");
		CashingApplyInfo info = userFundActionMapper.findUserFundActionById(fundId);
		return info;
	}

	@Override
	public List<UserFundAction> findByActionTypeInManager(String userId, Integer actionType, int status,
			Pageable pager) {
		// TODO Auto-generated method stub
		LogUtil.info(logger, "正在执行管理员查询相关提现信息。。。。。。");
		return userFundActionMapper.findByActionTypeInManager(userId, actionType, status, pager);
	}

	/**
	 * 花费余额
	 * @param @param userFundAction
	 * @param @return
	 * @author guohao
	 * @date 2017年1月11日 上午11:26:45
	 * @since $
	 *  
	 * @see com.nuanshui.heatedloan.fund.facade.UserFundActionService#payGoodsMoney(com.nuanshui.heatedloan.fund.model.UserFundAction)
	 *
	 */
	@SuppressWarnings("unused")
	@Override
	@Transactional(value = TransactionManagerType.FUND_TRANSACTION_MANAGER)
	public boolean payGoodsMoney(UserFundAction userFundAction) {	
		userFundActionMapper.saveUserFundAction(userFundAction);
		return true;
	}

	@Override
	@Transactional(value = TransactionManagerType.FUND_TRANSACTION_MANAGER)
	public String payFreezeFund(Long money, String currentUserId) {
		String orderNum = orderNumGenerate.getDealNum(AccountBillBizType.MARGIN);
		LogUtil.info(logger, "缴纳保证金" + money / 100 + "元");
		Long price = loadTotalFund(currentUserId).asLong();
		if (price.intValue() < money.intValue())
			error("余额不足");
		// 插入账单表
		UserAccountBill userAccountBill = new UserAccountBill();
		userAccountBill.setUserId(currentUserId);
		userAccountBill.setDealNum(orderNum);
		userAccountBill.setMoney(money * -1);
		userAccountBill.setName(NAME);
		userAccountBill.setStatus(FreezeFundState.COMPLETE);
		//userAccountBill.setType(AccountBillType.MARGIN);
		userAccountBill.setPlatform("YE");
		userAccountBill.setSubType(FreezeFundActionType.PAY_BOND_MONEY);
		userAccountBillMapper.insertBillRecord(userAccountBill);

		// 插入余额表
		UserFundAction userFundAction = new UserFundAction();
		userFundAction.setActionType(FundActionType.FREEZE_FUND+"");
		userFundAction.setStatus(FundActionState.COMPLETE);
		userFundAction.setUserId(currentUserId);
		userFundAction.setMoney(Long.valueOf(-1 * money));
		userFundAction.setPlatform("YE");
		userFundAction.setDealNum(orderNum);
		userFundAction.setBizId(userAccountBill.getId());
		userFundActionMapper.saveUserFundAction(userFundAction);

		// 插入保证金表
		UserFreezeFundAction userFreezeFundAction = new UserFreezeFundAction();
		userFreezeFundAction.setPlatform("YE");
		userFreezeFundAction.setUserId(currentUserId);
		userFreezeFundAction.setMoney(money);
		userFreezeFundAction.setStatus(FreezeFundState.COMPLETE);
		userFreezeFundAction.setType(FreezeFundActionType.PAY_BOND_MONEY);
		userFreezeFundAction.setDealNum(orderNum);
		String id = userAccountBill.getId();
		userFreezeFundAction.setBizId(id);
		userFreezeFundActionMapper.saveUserFreezeFundAction(userFreezeFundAction);

		return orderNum;
	}

	@Override
	public UserFundActionDetail loadUserFundActionDetailByDealNum(String dealNum) {

		return userFundActionMapper.loadUserFundActionDetailByDealNum(dealNum);
	}

	@Override
	@Transactional(value = TransactionManagerType.FUND_TRANSACTION_MANAGER)
	public boolean drawCash(Long money, String userId, String platform) {
		Long hasMoney = this.loadTotalFund(userId).asLong();
		if (hasMoney < money) {
			return false;
		}
		String dealNum = orderNumGenerate.getDealNum(AccountBillBizType.DRAW_CASH);
		UserFundAction userFundAction = new UserFundAction();
		userFundAction.setActionType(FundActionType.DRAW_CASH+"");
		userFundAction.setStatus(FundActionState.AUDICT);
		userFundAction.setUserId(userId);
		userFundAction.setMoney(-1 * money);
		userFundAction.setPlatform(platform);
		userFundAction.setDealNum(dealNum);
		this.saveUserFundAction(userFundAction);
		return false;
	}

	@Override
	@Transactional(value = TransactionManagerType.FUND_TRANSACTION_MANAGER)
	public DubboResponse useFund(UseFundForm useFundForm) {
		String dealNum = orderNumGenerate.getDealNum(useFundForm.getBillBizType());
		// 插入账单表
		UserAccountBill userAccountBill = new UserAccountBill();
		userAccountBill.setUserId(useFundForm.getUserId());
		userAccountBill.setDealNum(dealNum);
		userAccountBill.setMoney(useFundForm.getPrice() * -1);
		userAccountBill.setName(useFundForm.getTitle());
		userAccountBill.setStatus(FreezeFundState.COMPLETE);
		//userAccountBill.setType(useFundForm.getBillType());
		userAccountBill.setBizId(useFundForm.getBizId());
		userAccountBill.setPlatform("YE");
		userAccountBill.setSubType(useFundForm.getSubBillType());
		userAccountBillMapper.insertBillRecord(userAccountBill);
		// 扣除金额
		UserFundAction userFundAction = new UserFundAction();
		userFundAction.setActionType(useFundForm.getActionType()+"");
		userFundAction.setStatus(FundActionState.COMPLETE);
		userFundAction.setUserId(useFundForm.getUserId());
		userFundAction.setMoney(useFundForm.getPrice() * -1);
		userFundAction.setPlatform("YE");
		userFundAction.setDealNum(dealNum);
		userFundAction.setBizId(userAccountBill.getId());
		userFundActionMapper.saveUserFundAction(userFundAction);

		// 确认使用的玉币
		UseJadeCurrencyForm useJadeCurrencyForm = new UseJadeCurrencyForm();
		useJadeCurrencyForm.setOrderNum(useFundForm.getOrderNum());
		useJadeCurrencyForm.setBillId(userAccountBill.getId());
		jadeCurrencyService.confirmUseJadeCurrency(useJadeCurrencyForm);
		DubboResponse response = new DubboResponse();
		response.setData(dealNum);

		return response;
	}

	/**
	 * 取消订单退还保证金和玉币
	 * 
	 * @param @return
	 * @author guohao
	 * @date 2016年8月2日 上午11:23:38
	 * @since $
	 */
	@Override
	@Transactional(value = TransactionManagerType.FUND_TRANSACTION_MANAGER)
	public DubboResponse refundUserFund(UseFundForm useFundForm) {

		DubboResponse response = new DubboResponse();
		String dealNum = orderNumGenerate.getDealNum(useFundForm.getBillBizType());

		UserAccountBill bill = userAccountBillMapper.loadByDealNum(useFundForm.getDealNum());
		if (bill == null) {// 账单不存在返回false
			response.setCode(DubboResponseCode.NOT_FOUND);// 表示
			return response;

		}
		// 退换余额账单记录
		UserAccountBill userAccountBill = new UserAccountBill();
		userAccountBill.setUserId(useFundForm.getUserId());
		userAccountBill.setDealNum(dealNum);
		// 管理员给用户退款，获取管理员输入的金额
		if (useFundForm.getPrice() != null && useFundForm.getPrice() > 0) {
			userAccountBill.setMoney(useFundForm.getPrice());
		} else {
			userAccountBill.setMoney(bill.getMoney() * -1);
		}
		userAccountBill.setName(useFundForm.getTitle());
		userAccountBill.setStatus(FreezeFundState.COMPLETE);
		//userAccountBill.setType(useFundForm.getBillType());
		userAccountBill.setBizId(useFundForm.getBizId());
		userAccountBill.setPlatform("YE");
		userAccountBill.setJadeCurrency(bill.getJadeCurrency());
		userAccountBill.setSubType(useFundForm.getSubBillType());
		userAccountBillMapper.insertBillRecord(userAccountBill);
		// 增加余额

		UserFundAction userFundAction = new UserFundAction();
		userFundAction.setActionType(useFundForm.getActionType()+"");
		userFundAction.setStatus(FundActionState.COMPLETE);
		userFundAction.setUserId(useFundForm.getUserId());
		// 管理员给用户退款，获取管理员输入的金额
		if (useFundForm.getPrice() != null && useFundForm.getPrice() > 0) {
			userFundAction.setMoney(useFundForm.getPrice());
		} else {
			userFundAction.setMoney(bill.getMoney() * -1);
		}
		userFundAction.setPlatform("YE");
		userFundAction.setDealNum(dealNum);
		userFundAction.setBizId(userAccountBill.getId());
		userFundActionMapper.saveUserFundAction(userFundAction);

		// 退还玉币
		jadeCurrencyService.refundSystemCurrencyUsc(useFundForm.getOrderNum());
		response.setData(dealNum);
		return response;

	}

	@Override
	public UserFundAction loadByDealNum(String dealNum) {
		return userFundActionMapper.loadUserFundByDealNum(dealNum);

	}

	@Override
	@Transactional(value = TransactionManagerType.FUND_TRANSACTION_MANAGER, readOnly = false)
	public void saveUserFundActionJustSave(UserFundAction userFundAction) {
		userFundActionMapper.saveUserFundAction(userFundAction);
	}

	@Override
	public Long loadSeverChargeByOrderId(String orderId) {
		return userFundActionMapper.loadSeverChargeByOrderId(orderId);
	}

	@Override
	@Transactional(value = TransactionManagerType.FUND_TRANSACTION_MANAGER, readOnly = false)
	public void insertFundActionDetail(UserFundActionDetail userFundActionDetail) {
		userFundActionMapper.insertFundActionDetail(userFundActionDetail);
	}

	@Override
	@Transactional(readOnly = false, value = TransactionManagerType.FUND_TRANSACTION_MANAGER)
	public String payMembershipFee(long money, String userId) {
		String orderNum = orderNumGenerate.getDealNum(AccountBillBizType.USER_MEMBER);
		LogUtil.info(logger, "充值寻玉会会员 "+money/100+" 元");
		UserAccountBill userAccountBill = new UserAccountBill();
		userAccountBill.setUserId(userId);
		userAccountBill.setDealNum(orderNum);
		userAccountBill.setMoney(money*-1);
		userAccountBill.setName("会员充值");
		userAccountBill.setStatus(FundActionState.CREATE); 
		//userAccountBill.setType(AccountBillType.USER_MEMBER);
		userAccountBill.setPlatform("WX");
		userAccountBill.setSubType(AccountBillType.USER_MEMBER);
		userAccountBillMapper.insertBillRecord(userAccountBill);
		return orderNum;
	}

	@Override
	@Transactional(readOnly = false, value = TransactionManagerType.FUND_TRANSACTION_MANAGER)
	public String loadBatchPayNum(String orderNumber, Long totalPrice,  String title, Integer batchOrderNumType) {
		//TODO 再处理
		
		
		return "";
	}
	
}
